#include "LevelLoader.h"


LevelLoader::LevelLoader(int level)
{
	//--------------------------------
	//Integer to string conversion
	//--------------------------------
	char level_str [10];
	itoa(level, level_str, 10);
	string map_file_name = std::string("level") + level_str  + "_map.txt";// + (string)level +"_map.txt";
	itoa(level, level_str, 10);
	string movables_file_name = std::string("level") + level_str  + "_movables.txt";// + (string)level +"_map.txt";

		
	mapfile = ifstream(map_file_name);		//!< CSS data for Map
	movablesfile = ifstream(movables_file_name); //!< CSS data for Movables

	if ( !mapfile || !movablesfile )
	{
		throw "The File Can Not Be Opened";
	}

	loadObjects();
}

vector<vector<Movable_type>> LevelLoader::getMapData()
{
	string line;
	vector <string> string_lines;
	vector <Movable_type> movable_line;
	vector <vector <Movable_type>> map;
	int i = 0; 

	while(getline(mapfile, line, '\n'))
	{
		map.push_back(movable_line);
		mapLineToMapElements(map.at(i), line);
		i++;
	}

	return map;

	
}

void LevelLoader::loadObjects()
{
	string line; 

	while(getline(movablesfile, line, '\n'))
	{
		movables_data_string.push_back(line);
	}
	
}


Point LevelLoader::getDigdugPosition()
{
	return stringToPoint(movables_data_string.at(0));
}

vector <Point> LevelLoader::getMonstersPosition()
{
	vector<Point> monster_data;
	
	for(int i = 1; i < movables_data_string.size(); i++)
	{
		monster_data.push_back(stringToPoint(movables_data_string.at(i)));
	}
	return monster_data;
}

Point LevelLoader::stringToPoint(string string_line)
{
	int i = string_line.find(',');
	int x_pos = atoi((string_line.substr(0,i)).c_str()); 
	string c = (string_line.substr(i+1,string_line.size()));
	int y_pos = atoi(c.c_str()); 

	Point point(x_pos-1, y_pos-1);//!NB Minus one as the grid starts at ZERO and not ONE

	return point; 
}

void LevelLoader::mapLineToMapElements(vector<Movable_type>& line_elements, const string &string_line)
{
    line_elements.clear();
	int start_pos = 0;
    int end_pos = 0;
    int word_lenght = 0;
    int i = 0;

    while (string_line[i])
    {
       while (string_line[i] == ',' && string_line[i])
       {
           i++;
       }
       start_pos = i;

        while (string_line[i] != ',' && string_line[i])
       {
           i++;
       }
       end_pos = i;
       word_lenght = end_pos - start_pos ;

       if(word_lenght > 0)
       {
           line_elements.push_back(stringToHolesAndSand(string_line.substr(start_pos, word_lenght)));
       }
    }
}

Movable_type LevelLoader::stringToHolesAndSand(string &s_type)
{
		if (s_type == "#")
			return SAND;
		else if (s_type == " ")
			return HOLE;
		else
			throw "BACKGROUND DATAFILE IS CORRUPT";
}